//index.js
var app = getApp();
var CN_Date = require('../date/getCNDate.js');
var getFormatDate = require('../../service/date.js');
const defLat = 39.90, //默认纬度
      defLng = 116.41, // 默认经度
      defCityName = "北京"; //默认北京
       
var util = require('../../utils/network.js')
var uuidv1 = require('../../utils/node-uuid/uuidv1');
Page({
    data: {
        imgUrls: [
            '../../image/fengjing.jpg',
            '../../image/pink.jpg',
            '../../image/heart.jpg'
        ],
        indicatorDots: true,
        autoplay: true,
        interval: 3000,
        duration: 1000,
        circular: true,
        loginTel: '',//登录框输入手机号
        loginNumcode: '',//登录框输入6为验证码
        loginImgcode: '',//登录框输入图片验证码
        getcode: '获取验证码',
        imgurl: '',//图片验证码
        message: '',//错误信息
        bShow: false,//错误信息显示隐藏
        bHide: false,//弹框显示隐藏
        uid: '',
        currentDepartDate: null,//当前显示的出发日期
        currentDepartCity: '',//当前显示的出发城市
        currentReachCity: '请选择',//当前目前地城市 默认显示
        searchCityHistoryList: []//查询历史记录按“出发地-目的地”为对象进行存储
    },
    onLoad: function() {
        // wx.showLoading({
        //     title: '正在加载中',
        // })
        var that = this;
        that.clearDepartReachList();
        
        if(!that.data.currentDepartCity) {
            //获取当前的地理位置经纬度信息
            that.getLocation();
        }

        // 登录
        var openId = (wx.getStorageSync('openId'))
        if (openId) {
            wx.getUserInfo({
                lang:'zh_CN',
                success: function (data) {
                    wx.hideLoading()
                    var avatarUrl = data.userInfo.avatarUrl
                    var nickName = data.userInfo.nickName
                    wx.setStorageSync('avatarUrl', avatarUrl)
                    wx.setStorageSync('nickName', nickName)
                    var token = util.token
                    wx.request({
                        url: util.main + '/user/qqAndroidLogin/',
                        data: {
                            "openid": wx.getStorageSync("openId"),
                            "sex": '1',
                            "nickname": '0975313',
                            "token": token,
                            "deviceid": "b93b52d0-0724-11e8-b14b-d76caa854d03"
                        },
                        method: "POST",
                        header: {
                            "Content-Type": "application/x-www-form-urlencoded"
                        },
                        success: function (res) {
                            if (res.statusCode == 200) {
                                if (res.data.phonenum == null || res.data.phonenum == '') {
                                    that.setData({
                                        bHide: true
                                    })
                  } else {     
                                    wx.setStorageSync("clienttoken", res.data.clienttoken)
                                    wx.setStorageSync("userId", res.data.id)
                                    wx.setStorageSync("userInfo", JSON.stringify(res.data))
                                }
                            }
                            console.log(res)
                        }
                    })
                    // 显示图片验证码
                    var uid = uuidv1()
                    that.setData({
                        uid: uid
                    })
                    //函数调用  
                    wx.request({
                        url: util.main + '/imagevalidate/createValidateImageToAndroidOrIOS',
                        data: {
                            "uuid": uid,
                            "devicetoken": "",
                            "clienttoken": "",
                            "clienttype": "weix",
                            "version": "1.0"
                        },
                        header: {
                            'content-type': ' text/html'
                        },
                        method: "GET",
                        dataType: "json",
                        success: function (res) {
                            that.setData({
                                imgurl: util.main + '/imagevalidate/createValidateImageToAndroidOrIOS?uuid=' + uid
                            })
                        }
                    })
                },
                fail: function () {
                    // fail
                    console.log("获取失败！")
                },
                complete: function () {
                    // complete
                    console.log("获取用户信息完成！")
                }
            })
        } else {
            wx.login({
                success: res => {
                    var code = res.code
                    console.log(code)
                    wx.request({
                      url: util.main + '/miniProgram/login',
                        data: {
                            js_code: code,
                            // grant_type: 'authorization_code'
                        },
                        success: function (res_user) {
                            //   var sessionKey = res_user.data.session_key
                            wx.setStorageSync('openId', res_user.data.openid)
                            // //   获取unionId
                            wx.getUserInfo({
                                withCredentials: true,
                                lang: 'zh_CN',
                                success: function (data) {
                                    wx.hideLoading()
                                    var avatarUrl = data.userInfo.avatarUrl
                                    var nickName = data.userInfo.nickName
                                    wx.setStorageSync('avatarUrl', avatarUrl)
                                    wx.setStorageSync('nickName', nickName)
                                    var token = util.token
                                    wx.request({
                                        url: util.main + '/user/qqAndroidLogin/',
                                        data: {
                                            "openid": wx.getStorageSync("openId"),
                                            "sex": '1',
                                            "nickname": '0975313',
                                            "token": token,
                                            "deviceid": "b93b52d0-0724-11e8-b14b-d76caa854d03"
                                        },
                                        method: "POST",
                                        header: {
                                            "Content-Type": "application/x-www-form-urlencoded"
                                        },
                                        success: function (res) {
                                            if (res.statusCode == 200) {
                                                if (res.data.phonenum == null || res.data.phonenum == '') {
                                                    that.setData({
                                                        bHide: true
                                                    })
                                                } else {
                                                    wx.setStorageSync("clienttoken", res.data.clienttoken)
                                                    wx.setStorageSync("userId", res.data.id)
                                                }
                                            }
                                            console.log(res)
                                        }
                                    })
                                    // 显示图片验证码
                                    var uid = uuidv1()
                                    that.setData({
                                        uid: uid
                                    })
                                    //函数调用  
                                    wx.request({
                                        url: util.main + '/imagevalidate/createValidateImageToAndroidOrIOS',
                                        data: {
                                            "uuid": uid,
                                            "devicetoken": "",
                                            "clienttoken": "",
                                            "clienttype": "weix",
                                            "version": "1.0"
                                        },
                                        header: {
                                            'content-type': ' text/html'
                                        },
                                        method: "GET",
                                        dataType: "json",
                                        success: function (res) {
                                            that.setData({
                                                imgurl: util.main + '/imagevalidate/createValidateImageToAndroidOrIOS?uuid=' + uid
                                            })
                                        }
                                    })
                                },
                                fail: function () {
                                    wx.showModal({
                                        title: '警告通知',
                                        content: '您点击了拒绝授权,将无法正常显示个人信息,点击确定重新获取授权。',
                                        showCancel: false,
                                        success: function (res) {
                                            if (res.confirm) {
                                                wx.openSetting({
                                                    success: (res) => {
                                                        if (res.authSetting["scope.userInfo"]) {////如果用户重新同意了授权登录
                                                            wx.login({
                                                                success: function (res_login) {
                                                                    if (res_login.code) {
                                                                        wx.getUserInfo({
                                                                            withCredentials: true,
                                                                            success: function (res_data) {
                                                                                wx.hideLoading()
                                                                                var avatarUrl = res_data.userInfo.avatarUrl
                                                                                var nickName = res_data.userInfo.nickName
                                                                                wx.setStorageSync('avatarUrl', avatarUrl)
                                                                                wx.setStorageSync('nickName', nickName)
                                                                            }
                                                                        })
                                                                    }
                                                                }
                                                            })
                                                        }
                                                    }
                                                })
                                            }
                                        }

                                    })
                                }
                            })
                        }
                    })
                }
            })
        }
    },
    // 生命周期函数--监听页面显示
    onShow: function() {
        var that = this,
        findname,cityname;
        if(wx.getStorageSync("departCityInfo")) {
            findname = wx.getStorageSync("departCityInfo").findname;
            findname = findname.slice(0,findname.length - 1);
        }
        if(wx.getStorageSync("reachCityInfo")) {
            cityname = wx.getStorageSync("reachCityInfo").cityname ? wx.getStorageSync("reachCityInfo").cityname : wx.getStorageSync("reachCityInfo").name;//接口文档里说cityname 和 name都是名称，目前cityname没有返回值，所以加了这个判断
            cityname = cityname.slice(0,cityname.length-1);
        }
        // 获取查询历史记录
        if(wx.getStorageSync("searchCityHistoryList")) {
            that.setData({searchCityHistoryList: wx.getStorageSync("searchCityHistoryList").data.slice(0, 3)});  
        }

        that.setData({
            currentDepartCity: findname ? findname : defCityName,
            currentReachCity: cityname ? cityname : '请选择',
            currentDepartDate: wx.getStorageSync("currentDepartDate")
        });
    },
    // 清空到达和目的地城市信息
    clearDepartReachList: function() {
        wx.removeStorageSync("departCityInfo");
        wx.removeStorageSync("reachCityInfo");

        var currentDate = new Date(),
            currentDepartDate = {
                yearmothday: getFormatDate.getFormatDate(new Date().getTime()),
                timestamp: new Date().getTime(),
                year: currentDate.getFullYear(),
                monthday: (currentDate.getMonth() + 1) + '月' + (currentDate.getDate()) + '日',//阳历月日
                nonglimonthday: CN_Date.GetMonthDay(currentDate.getFullYear(), currentDate.getMonth() + 1, currentDate.getDate()),//农历月日
                weekday: CN_Date.getWeekDay(currentDate.getDay())//周几
            },
            that = this;
        that.setData({currentDepartDate: currentDepartDate});
        wx.setStorageSync("currentDepartDate", that.data.currentDepartDate);
    },
    //获取当前的地理位置经纬度信息
    getLocation: function() {
        var that = this;
        wx.getLocation({
            type: 'wgs84', 
            success: function(res) {
                //console.log('获取到的定位信息',res);
                that.locationCity({
                    longitude: res.longitude,
                    latitude: res.latitude
                });
            },
            fail: function(res) {
                // 定位失败后默认城市
                that.locationCity({
                    longitude: that.data.defLng,
                    latitude: that.data.defLat
                });
            }
        });
    },
    //根据经纬度信息获取定位出发城市的名字，比如北京市
    locationCity: function(obj) {
        var that = this;
        wx.request({
            url: 'https://api.map.baidu.com/geocoder/v2/?ak=OxUmBw5HfbmvmAcSQr1gRMHU&location=' + obj.latitude + ',' + obj.longitude + '&output=json',
            data: {},
            header: {
                'Content-Type': 'application/json'
            },
            success: function (res) {
                //console.log('根据经纬度获取城市信息',res);
                var cityName = res.data.result.addressComponent.city;
                cityName = cityName.slice(0,cityName.length-1);

                that.setData({currentDepartCity: cityName});
                that.findLocationCity(res.data.result.addressComponent.city);
            },
            fail: function () {
                that.setData({currentDepartCity: defCityName});
                that.findLocationCity(that.data.currentDepartCity);
            }
        });
    },
    //根据城市名字获取定位出发城市的信息
    findLocationCity: function(cityName) {
        var that = this;
        var token = util.token
        wx.request({
            url: app.getApi("api_better_departure"),
            data: {cityname: cityName,token:token},
            method: "GET",

            header: {
                'content-type': 'application/json'
            },
            success: function(res) {
                // console.log(res)
                //console.log('根据城市名获取定位城市信息',res);
                var findname;
                if(res.data.length) {
                    findname = res.data[0].findname;

                    findname = findname.slice(0,findname.length - 1);

                    wx.setStorageSync("departCityInfo", res.data[0]);
                    that.setData({currentDepartCity: findname});
                }
            },
            fail: function(res) {
                //console.log('获取定位城市信息失败',res);
            }
        });
    },
    // 选中出发到达城市
    getGo: function (e) {
        //isgo 0:出发城市  1:到达城市
        var isgo = e.currentTarget.dataset.isgo;
        wx.navigateTo({
            url: '../gocity/gocity?isgo='+isgo
        });
    },
    // 选择出发日期
    changedate: function () {
        wx.navigateTo({
            url: '../date/date'
        })
    },
    //查询
    search: function() {
        const aDepartReachCity = wx.getStorageSync("searchCityHistoryList").data || [];

        // 出发和到达都选中时
        const departCity = wx.getStorageSync("departCityInfo")
        const reachCity = wx.getStorageSync("reachCityInfo")

        if (!reachCity) {
          wx.showToast({
            title: '错误',
            icon: 'none',
            image: '/image/error.png',
            duration: 2000
          })
          return
        }
        var cityLen;

        if (!(cityLen = aDepartReachCity.length)) {
          aDepartReachCity.push({ departCity, reachCity })
        } else {
          let invoked = true
          for (let i = 0; i < cityLen; i++) {
            const item = aDepartReachCity[i]
            if (item && item.reachCity.name == reachCity.name && item.departCity.findname == departCity.findname) {
              invoked = false
            }
          }
          if (invoked)
            aDepartReachCity.unshift({ departCity, reachCity })
        }

        wx.setStorageSync("searchCityHistoryList", { data: aDepartReachCity.slice(0, 3) });

        wx.navigateTo({
          url: '../search/search'
        });

    },
    //登录框输入手机号
    loginTel: function (e) {
        this.setData({
            loginTel: e.detail.value
        })
    },
    //登录框输入6为验证码
    loginNumcode: function (e) {
        this.setData({
            loginNumcode: e.detail.value
        })
    },
    //登录框输入图片验证码
    loginImgcode: function (e) {
        this.setData({
            loginImgcode: e.detail.value
        })
    },
    //   改变验证码图片
    changeImg: function () {
        var that = this
        var uid = uuidv1()
        that.setData({
            uid: uid
        })
        console.log(uid)
        //函数调用  
        wx.request({
            url: util.main + '/imagevalidate/createValidateImageToAndroidOrIOS',
            data: {
                "uuid": uid,
                "token": {
                    "devicetoken": "",
                    "clienttoken": "",
                    "clienttype": "weix",
                    "version": "1.0"
                }
            },
            method: "GET",
            dataType: "json",
            success: function (res) {
                that.setData({
                    imgurl: util.main + '/imagevalidate/createValidateImageToAndroidOrIOS?uuid=' + uid
                })
            }
        })
    },
    //   获取验证码
    getcode: function () {
        var that = this
        var uid = that.data.uid
        var loginTel = that.data.loginTel
        var loginImgcode = that.data.loginImgcode
        var openId = wx.getStorageSync("openId")
        var token = util.token
        if (loginTel == '') {
            that.setData({
                message: '请输入正确的手机号',
                bShow: true
            })
        } else if (loginImgcode == '') {
            that.setData({
                message: '请输入正确的图片验证码',
                bShow: true
            })
        } else if (loginTel != '' && loginImgcode != '') {
            wx.request({
                url: util.main + '/sms/association',
                data: "phone=" + that.data.loginTel + "&type=QQ&openid=" + openId + "&deviceid=" + openId + "&randomverifyCode=" + that.data.loginImgcode + "&token=" + token + "&uuid=" + uid,
                header: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                method: "POST",
                success: function (res) {
                    console.log(res)
                    if (res.statusCode == 200) {
                        var wait = 181
                        var time = setInterval(function () {
                            wait -= 1
                            that.setData({
                                getcode: wait + 's',
                                disabled: true
                            })
                            if (wait < 1) {
                                wait == 10
                                clearInterval(time)
                                that.setData({
                                    getcode: '获取验证码',
                                    disabled: false
                                })
                            }
                        }, 1000)
                        that.setData({
                            message: res.data.message,
                            bShow: true
                        })
                    } else {
                        that.setData({
                            message: res.data.message,
                            bShow: true
                        })
                    }
                    if (that.data.bShow) {
                        setTimeout(function () {
                            that.setData({
                                bShow: false
                            })
                        }, 2000)
                    }
                }
            })
        }
        if (that.data.bShow) {
            setTimeout(function () {
                that.setData({
                    bShow: false
                })
            }, 2000)
        }
    },
    // 登录
    formSubmit: function () {
        var that = this
        var token = util.token
        wx.request({
            url: util.main + '/user/association',
            data: {
                "phone": that.data.loginTel,
                "checkcode": that.data.loginNumcode,
                "deviceid": wx.getStorageSync("openId"),
                "token": token,
                "uuid": 'b93b52d0-0724-11e8-b14b-d76caa854d03'
            },
            header: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            method: "POST",
            success: function (res) {
                if (res.statusCode == 200) {
                    that.setData({
                        bHide: false
                    })
                } else {
                    that.setData({
                        message: res.data[0].message,
                        bShow: true
                    })
                }
                if (that.data.bShow) {
                    setTimeout(function () {
                        that.setData({
                            bShow: false
                        })
                    }, 2000)
                }
                console.log(res)
            }
        })
    },
    onShareAppMessage () {
        // 用户点击右上角分享
        return {
            title: 'Bus365', // 分享标题
            desc: '订车票', // 分享描述
            path: '/pages/index/index' // 分享路径
        }
    }
})
